import { FC, useEffect, useRef, useState } from 'react'
import CountUp from 'react-countup'

import './OverviewBox.less'

export type OverviewBoxProps = {
  title: string
  /** 环比 */
  qoqValue?: number
  /** 同比 */
  yoyValue?: number
  iconPath: string
  color: 'red' | 'green'
  entId: string
  dateType: string
}

function getTextColorFromValue(value: number) {
  return value < 0 ? '#66CCAA' : value > 0 ? '#FF6666' : '#ffffff'
}

function getLabelFromDateType(dateType: string) {
  switch (dateType) {
    case 'y':
      return '去年'
    case 'q':
      return '上季度'
    case 'm':
      return '上月'
    default:
      return ''
  }
}

const OverviewBox: FC<OverviewBoxProps> = ({
  title,
  qoqValue = 0,
  yoyValue = 0,
  iconPath,
  color,
  entId,
  dateType
}) => {
  const entIdRef = useRef<string>(entId)
  const dateTypeRef = useRef<string>(dateType)
  // 环比
  const [qoqSum, setQoqSum] = useState<number>(0)
  const qoqSumRef = useRef<number>(0)
  const [prevQoqSum, setPrevQoqSum] = useState<number>(0)
  const prevQoqSumRef = useRef<number>(0)
  const [endQoqSum, setEndQoqSum] = useState<number>(0)
  const endQoqSumRef = useRef<number>(0)

  // 环比
  const [yoySum, setYoySum] = useState<number>(0)
  const yoySumRef = useRef<number>(0)
  const [prevYoySum, setPrevYoySum] = useState<number>(0)
  const prevYoySumRef = useRef<number>(0)
  const [endYoySum, setEndYoySum] = useState<number>(0)
  const endYoySumRef = useRef<number>(0)

  // timeout
  const qoqSumTimeoutIdRef = useRef<any>()
  const yoySumTimeoutIdRef = useRef<any>()

  //数据/时间 分组
  const qoqSumUpGroupRef = useRef<{
    countGroup: number[]
    timeGroup: number[]
  }>({
    countGroup: [],
    timeGroup: []
  })
  const yoySumUpGroupRef = useRef<{
    countGroup: number[]
    timeGroup: number[]
  }>({
    countGroup: [],
    timeGroup: []
  })

  const qoqSumUpGroupIndexRef = useRef<number>(0)
  const yoySumUpGroupIndexRef = useRef<number>(0)

  useEffect(() => {
    if (entIdRef.current !== entId) {
      clearCountUp()
      // 环比
      setQoqSum(0)
      qoqSumRef.current = 0
      setPrevQoqSum(0)
      prevQoqSumRef.current = 0
      setEndQoqSum(0)
      endQoqSumRef.current = 0
      qoqSumUpGroupRef.current = {
        countGroup: [],
        timeGroup: []
      }
      qoqSumUpGroupIndexRef.current = 0

      // 同比
      setYoySum(0)
      yoySumRef.current = 0
      setPrevYoySum(0)
      prevYoySumRef.current = 0
      setEndYoySum(0)
      endYoySumRef.current = 0
      yoySumUpGroupRef.current = {
        countGroup: [],
        timeGroup: []
      }
      yoySumUpGroupIndexRef.current = 0
    }

    // 日期类型变化时
    if (dateTypeRef.current !== dateType) {
      // 环比
      qoqSumUpGroupRef.current = {
        countGroup: [],
        timeGroup: []
      }
      qoqSumUpGroupIndexRef.current = 0

      prevQoqSumRef.current = endQoqSumRef.current
      setPrevQoqSum(endQoqSumRef.current)
      setEndQoqSum(qoqValue)
      endQoqSumRef.current = qoqValue

      // 同比
      yoySumUpGroupRef.current = {
        countGroup: [],
        timeGroup: []
      }
      yoySumUpGroupIndexRef.current = 0

      prevYoySumRef.current = endYoySumRef.current
      setPrevYoySum(endYoySumRef.current)
      setEndYoySum(yoyValue)
      endYoySumRef.current = yoyValue
    } else {
      // 环比
      setQoqSum(qoqValue)
      qoqSumRef.current = qoqValue
      if (qoqValue !== 0) {
        setEndQoqSum(qoqValue)
        endQoqSumRef.current = qoqValue
      }

      // 同比
      setYoySum(yoyValue)
      yoySumRef.current = yoyValue
      if (yoyValue !== 0) {
        setEndYoySum(yoyValue)
        endYoySumRef.current = yoyValue
      }
    }
  }, [qoqValue, yoyValue, dateType, entId])

  function clearCountUp() {
    // 环比
    if (qoqSumTimeoutIdRef.current) {
      clearTimeout(qoqSumTimeoutIdRef.current)
    }

    // 同比
    if (yoySumTimeoutIdRef.current) {
      clearTimeout(yoySumTimeoutIdRef.current)
    }
  }

  // 环比
  function _recursionQoqSumSetStartEndCount(gorupIndex: number) {
    if (gorupIndex > qoqSumUpGroupRef.current.countGroup.length - 1) {
      if (qoqSumTimeoutIdRef.current) {
        clearTimeout(qoqSumTimeoutIdRef.current)
      }
      if (qoqSumRef.current !== qoqSumRef.current) {
        console.error(
          `endQoqSumRef.current 【${endQoqSumRef.current}】!==qoqSumRef 【${qoqSumRef.current}】`
        )
      }
      return
    }
    const timeoutTime = Math.max(
      1,
      qoqSumUpGroupRef.current.timeGroup[gorupIndex] - 1
    ) //CountUp duration需要1s
    if (qoqSumTimeoutIdRef.current) {
      clearTimeout(qoqSumTimeoutIdRef.current)
    }
    qoqSumTimeoutIdRef.current = setTimeout(() => {
      if (gorupIndex === 0) {
        //初始化时是从1开始的，以后每次更新是从0开始的
        prevQoqSumRef.current = endQoqSumRef.current
      } else if (gorupIndex > 0) {
        prevQoqSumRef.current +=
          qoqSumUpGroupRef.current.countGroup[gorupIndex - 1]
      }
      setPrevQoqSum(prevQoqSumRef.current)

      const currEndCount =
        qoqSumUpGroupRef.current.countGroup[gorupIndex] + prevQoqSumRef.current
      endQoqSumRef.current = currEndCount

      setEndQoqSum(currEndCount)
    }, timeoutTime * 1000)
  }

  const handleQoqCountUpEnd = () => {
    qoqSumUpGroupIndexRef.current += 1
    _recursionQoqSumSetStartEndCount(qoqSumUpGroupIndexRef.current)
  }

  // 同比
  function _recursionYoySumSetStartEndCount(gorupIndex: number) {
    if (gorupIndex > yoySumUpGroupRef.current.countGroup.length - 1) {
      if (yoySumTimeoutIdRef.current) {
        clearTimeout(yoySumTimeoutIdRef.current)
      }
      if (endYoySumRef.current !== yoySumRef.current) {
        console.error(
          `endZhengWuSumRef.current 【${endYoySumRef.current}】!==zhengWuSumRef 【${yoySumRef.current}】`
        )
      }
      return
    }
    const timeoutTime = Math.max(
      1,
      yoySumUpGroupRef.current.timeGroup[gorupIndex] - 1
    ) //CountUp duration需要1s
    if (yoySumTimeoutIdRef.current) {
      clearTimeout(yoySumTimeoutIdRef.current)
    }
    yoySumTimeoutIdRef.current = setTimeout(() => {
      if (gorupIndex === 0) {
        //初始化时是从1开始的，以后每次更新是从0开始的
        prevYoySumRef.current = endYoySumRef.current
      } else if (gorupIndex > 0) {
        prevYoySumRef.current +=
          yoySumUpGroupRef.current.countGroup[gorupIndex - 1]
      }
      setPrevYoySum(prevYoySumRef.current)

      const currEndCount =
        yoySumUpGroupRef.current.countGroup[gorupIndex] + prevYoySumRef.current
      endYoySumRef.current = currEndCount

      setEndYoySum(currEndCount)
    }, timeoutTime * 1000)
  }

  const handleYoyCountUpEnd = () => {
    yoySumUpGroupIndexRef.current += 1
    _recursionYoySumSetStartEndCount(yoySumUpGroupIndexRef.current)
  }

  return (
    <div className={`governance-dffectiveness-analysis-overview-box ${color}`}>
      <div className="title-box">
        <div className={`title-box-inner ${color}`}>
          <img src={iconPath} style={{ width: 34, height: 25 }} alt="" />
          <span style={{ marginLeft: 8, fontSize: 18 }}>{title}</span>
        </div>
      </div>
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }}
      >
        <div style={{ flex: '1 1 50%', textAlign: 'center' }}>
          <div
            style={{
              fontSize: 24,
              fontFamily: 'ZQKHY',
              color: getTextColorFromValue(qoqValue)
            }}
          >
            {qoqValue > 0 && '+'}
            <CountUp
              start={prevQoqSum}
              end={endQoqSum}
              duration={1}
              onEnd={handleQoqCountUpEnd}
            />
            <span style={{ fontFamily: 'PuHuiTi-Bold' }}>%</span>
          </div>
          <div style={{ fontSize: 14 }}>
            环比{getLabelFromDateType(dateType)}
          </div>
        </div>
        <div className={`divider ${color}`} style={{ flex: '0 0 1px' }}></div>
        <div style={{ flex: '1 1 50%', textAlign: 'center' }}>
          <div
            style={{
              fontSize: 24,
              fontFamily: 'ZQKHY',
              color: getTextColorFromValue(yoyValue)
            }}
          >
            {yoyValue > 0 && '+'}
            <CountUp
              start={prevYoySum}
              end={endYoySum}
              duration={1}
              onEnd={handleYoyCountUpEnd}
            />
            <span style={{ fontFamily: 'PuHuiTi-Bold' }}>%</span>
          </div>
          <div style={{ fontSize: 14 }}>
            同比{getLabelFromDateType(dateType)}
          </div>
        </div>
      </div>
    </div>
  )
}

export default OverviewBox
